package com.dkcd.chenshiproject.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.dkcd.chenshiproject.MainActivity;
import com.dkcd.chenshiproject.R;
import com.dkcd.chenshiproject.entity.Song;
import com.dkcd.chenshiproject.service.MusicPlayerService;
import com.dkcd.chenshiproject.util.ArtworkUtils;
import com.dkcd.chenshiproject.util.MusicUtils;
import com.dkcd.chenshiproject.util.SPUtils;

import java.util.List;

public class MusicPlayerActivity extends AppCompatActivity implements View.OnClickListener {

    private List<Song> musicData = MainActivity.musicData;

    //播放类型 为2,多曲循环;
    private int musicPlayerType = 2;
    private int musicPlayerActionType = 0;
    private ImageButton musicPlayStyleImageButton;
    private ImageButton musicPlayerAction;
    private ImageView songBannerImage;
    private TextView songNameTitle;
    private TextView singerName;
    private TextView musicEndTime;
    private TextView musicStartTime;
    private SeekBar musicPlayerSeekBar;
    private int musicId;
    private Messenger messenger = MainActivity.messenger;
    private boolean bound = MainActivity.bound;
    public static Handler handlers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);
        init();
        initView();
        initDefaultValue();
        handlear();
        musicPlayerServiceStart();

        if (MusicPlayerService.musicPlaying) {
            Log.e("TAG", "onCreate: 设置为暂停按钮" );
            musicPlayerActionType = 1;
            musicPlayerAction.setImageDrawable(getResources().getDrawable(R.drawable.pause_circle_icon));
        }else {
            Log.e("TAG", "onCreate: 设置为播放按钮" );
            musicPlayerActionType = 0;
            musicPlayerAction.setImageDrawable(getResources().getDrawable(R.drawable.play_circle_icon));
        }

        flashSeekBarProgress();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private void init(){
        musicPlayStyleImageButton = (ImageButton)findViewById(R.id.music_play_style);
        musicPlayerAction = (ImageButton)findViewById(R.id.music_play_action);
        songBannerImage = (ImageView)findViewById(R.id.song_banner_image);
        songNameTitle = (TextView) findViewById(R.id.song_name_title);
        singerName = (TextView) findViewById(R.id.singer_name);
        musicEndTime = (TextView) findViewById(R.id.music_end_time);
        musicStartTime = (TextView) findViewById(R.id.music_start_time);
        musicPlayerSeekBar = (SeekBar) findViewById(R.id.music_player_seek_bar);

        //获取当前播放歌曲的ID；
        Bundle bundle = getIntent().getExtras();
        musicId = bundle.getInt("musicId");
    }

    private void initView(){
        Song song = musicData.get(musicId);
        showAlbumImage(song);
        songNameTitle.setText(song.song);
        singerName.setText(song.singer);
        if (song.duration/1000/60>=10){
            musicEndTime.setText(MusicUtils.formatTime(song.duration));
        }else {
            musicEndTime.setText("0"+(MusicUtils.formatTime(song.duration)));
        }
        musicPlayerSeekBar.setMax(song.duration);
        changeSeekBaryProgress();
    }

    /**
     *
     * @author ChenShi
     * @version：1.0
     * @date
     * 描述: 刷新进度条
     *
     */
    private void flashSeekBarProgress(){
        Message obtain = Message.obtain(null, MusicPlayerService.FLASH_SEEK_BAR_PROGRESS, 0, 0);
        try {
            messenger.send(obtain);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @author ChenShi
     * @version：1.0
     * @date
     * 描述: 默认初始值 initDefaultValue
     *
     */
    private void initDefaultValue(){
        Integer musicPlayerTypeValue = (Integer)SPUtils.getValue(this, "musicPlayerType", 2);
        if (musicPlayerTypeValue != null){
            Log.e("TAG", "initDefaultValue: 更改的播放模式为"+musicPlayerTypeValue );
            musicPlayerType = musicPlayerTypeValue;
        }else {
            musicPlayerType = 2;
            SPUtils.putValue(this,"musicPlayerType",musicPlayerType);
        }
        switch (musicPlayerType){
            case 1:{
                musicPlayStyleImageButton.setImageDrawable(getResources().getDrawable(R.drawable.repeat_once_icon));
            }break;
            case 2:{
                musicPlayStyleImageButton.setImageDrawable(getResources().getDrawable(R.drawable.repeat_icon));
            }break;
            case 3:{
                musicPlayStyleImageButton.setImageDrawable(getResources().getDrawable(R.drawable.shuffle_icon));
            }break;
            default:
                break;
        }
    }

    /**
     *
     * @author ChenShi
     * @version：1.0
     * @date
     * 描述: 展示专辑图片
     *
     */

    private void showAlbumImage(Song song){
        Bitmap artwork = ArtworkUtils.getArtwork(this, song.song,
                Long.parseLong(song.songId), Long.parseLong(song.albumId), true);
        songBannerImage.setImageBitmap(artwork);
    }

    /**
     *
     * @author ChenShi
     * @version：1.0
     * @date
     * 描述: 创建MusicPlayer 服务
     *
     */
    private void musicPlayerServiceStart(){
        Log.e("TAG", "musicPlayerServiceStart: 开始musicPlayerServiceStart "+bound );
        if (bound){
            Log.e("TAG", "musicPlayerServiceStart: 向MusicService发送msg");
            Message obtain = Message.obtain(null, MusicPlayerService.SELECT_MUSIC, 0, 0);
            Bundle bundle = new Bundle();
            bundle.putInt("musicId",musicId);
            bundle.putInt("musicPlayerType",musicPlayerType);
            bundle.putString("maker",getIntent().getExtras().getString("maker"));
            obtain.setData(bundle);
            try {
                messenger.send(obtain);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @author ChenShi
     * @version：1.0
     * @date
     * 描述: 点击事件
     *
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.music_player_back){
            Log.e("TAG", "onClick: 点击" );
            this.finish();

        }else if (id == R.id.music_play_style){
            Log.e("TAG", "onClick: 点击改变播放状态" );
            musicPlayerTypeChanged();
            Message obtain = Message.obtain(null, MusicPlayerService.PLAYER_TYPE_CHANGED, 0, 0);
            Bundle bundle = new Bundle();
            bundle.putInt("musicPlayerType",musicPlayerType);
            obtain.setData(bundle);
            try {
                messenger.send(obtain);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }else if (id == R.id.music_play_previous){
            Log.e("TAG", "onClick: 点击播放上一首" );
            musicPlayerSeekBar.setProgress(0);
            musicPlayerActionType = 1;
            musicPlayerAction.setImageDrawable(getResources().getDrawable(R.drawable.pause_circle_icon));
            Message obtain = Message.obtain(null, MusicPlayerService.PREVIOUS_MUSIC, 0, 0);
            try {
                messenger.send(obtain);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }else if (id == R.id.music_play_action){
            Log.e("TAG", "onClick: 点击开始播放" );
            musicPlayerActionChanged();

        }else if (id == R.id.music_play_next){
            musicPlayerSeekBar.setProgress(0);
            Log.e("TAG", "onClick: 点击播放下一首" );
            musicPlayerActionType = 1;
            musicPlayerAction.setImageDrawable(getResources().getDrawable(R.drawable.pause_circle_icon));
            Message obtain = Message.obtain(null, MusicPlayerService.NEXT_MUSIC, 0, 0);
            try {
                messenger.send(obtain);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }else if (id == R.id.music_pavilion_list){

        }else if (id == R.id.song_banner_image){
            Intent intent = new Intent(this, SongBannerImageActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("song",musicData.get(musicId));
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    /**
     *
     * @author ChenShi
     * @version：1.0
     * @date
     * 描述: 播放状态 正在播放==1 停止播放==0
     *
     */
    private void musicPlayerActionChanged() {
        if (musicPlayerActionType == 0){
            musicPlayerActionType = 1;
            musicPlayerAction.setImageDrawable(getResources().getDrawable(R.drawable.pause_circle_icon));
            Message obtain = Message.obtain(null, MusicPlayerService.START_MUSIC, 0, 0);
            try {
                messenger.send(obtain);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }else {
            musicPlayerActionType = 0;
            musicPlayerAction.setImageDrawable(getResources().getDrawable(R.drawable.play_circle_icon));
            Message obtain = Message.obtain(null, MusicPlayerService.STOP_MUSIC, 0, 0);
            try {
                messenger.send(obtain);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @author ChenShi
     * @version：1.0
     * @date
     * 描述: 更改播放类型
     * type: 单曲循环==1  多曲循环==2  随机播放==3
     *
     */
    private void musicPlayerTypeChanged(){
        musicPlayerType++;
        if (musicPlayerType>3){
            musicPlayerType = 1;
        }
        switch (musicPlayerType){
            case 1:{
                Log.e("TAG", "onClick: 单曲循环状态" );
                musicPlayStyleImageButton.setImageDrawable(getResources().getDrawable(R.drawable.repeat_once_icon));
            }break;
            case 2:{
                Log.e("TAG", "onClick: 多曲循环状态" );
                musicPlayStyleImageButton.setImageDrawable(getResources().getDrawable(R.drawable.repeat_icon));
            }break;
            case 3:{
                Log.e("TAG", "onClick: 随机播放状态" );
                musicPlayStyleImageButton.setImageDrawable(getResources().getDrawable(R.drawable.shuffle_icon));
            }break;
            default:
                break;
        }
        SPUtils.putValue(this,"musicPlayerType",musicPlayerType);
    }

    /**
     *
     * @author ChenShi
     * @version：1.0
     * @date
     * 描述: 更新进度条
     *
     */
    private void updateProgressBar(Message message){
        Bundle data = message.getData();
        int progress = data.getInt("progress");
        String actionTime = data.getString("actionTime");
        musicPlayerSeekBar.setProgress(progress);
        musicStartTime.setText(actionTime);
    }

    public void handlear(){
        handlers = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                switch (msg.what){
                    case MusicPlayerService.CHANGE_MUSIC_ID:{
                        musicId = msg.getData().getInt("musicId");
                        musicPlayerSeekBar.setProgress(0);
                        initView();
                    }break;
                    case MusicPlayerService.SEEK_BAR_UPDATE:{
                        updateProgressBar(msg);
                    }break;
                    case MusicPlayerService.FLASH_SEEK_BAR:{
                        int flashProgress = msg.getData().getInt("FlashProgress");
                        boolean mediaPlayerIsPlaying = msg.getData().getBoolean("mediaPlayerIsPlaying");
                        if (MusicPlayerService.musicPlaying){
                            musicPlayerActionType = 1;
                            musicPlayerAction.setImageDrawable(getResources().getDrawable(R.drawable.pause_circle_icon));
                        }
                        musicPlayerSeekBar.setProgress(flashProgress);
                    }break;
                }
                return false;
            }
        });
    }

    /**
     *
     * @author ChenShi
     * @version：1.0
     * @date
     * 描述: 滑动进度条
     *
     */
    private void changeSeekBaryProgress(){
        musicPlayerSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                int progress = seekBar.getProgress();
                if (progress/1000/60>=10){
                    musicStartTime.setText(MusicUtils.formatTime(progress));
                }else {
                    musicStartTime.setText(0+MusicUtils.formatTime(progress));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                Message obtain = Message.obtain(null, MusicPlayerService.CHANGE_SEEK_BAR_PROGRESS, 0, 0);
                Bundle bundle = new Bundle();
                bundle.putInt("progress",progress);
                obtain.setData(bundle);
                try {
                    messenger.send(obtain);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }
        });
    }


}